import requests
import json

def read_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        print(f'文件 {file_path} 未找到.')
    except Exception as e:
        print(f'读取文件时发生错误: {e}')

# Ollama 的地址和端口（默认是 11434）
ollama_url = "http://localhost:11434/api/generate"
 
data = {
    "model": "deepseek-r1:7b", 
    "prompt":read_file('语料库.md')+'真棒', 
    "stream": True,
}

try:
    # 发送 POST 请求到 Ollama API，启用流式传输
    with requests.post(f"{ollama_url}", json=data, stream=True) as response:
        # 检查响应状态码
        if response.status_code == 200:
            if "application/x-ndjson" in response.headers.get("Content-Type").lower():
                for line in response.iter_lines():
                    if line:
                        data = json.loads(line.decode('utf-8').strip())
                        print(data['response'],end="")
                        if data.get("done"):
                            print("\n")
                            break
        else:
            print("Error:", response.status_code, response.text)
except requests.exceptions.ConnectionError as e:
    print("无法连接到 Ollama API，请检查服务器是否启动并且 URL 是否正确。")
    print("详细错误信息:", e)

